package com.koudai.reader.conponment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koudai.reader.ReadBookActivity;
import com.koudai.reader.android.R;
import com.koudai.reader.db.SingleDAO;
import com.koudai.reader.util.Constant;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.util.UnZip;
import com.koudai.reader.util.Utils;
import com.koudai.reader.vo.Book;
import com.koudai.reader.vo.EndUser;
import com.umeng.analytics.MobclickAgent;

/*
 * for app list adapter
 */
public class ListViewAdapter extends BaseAdapter {
    public int count = 0;
    LayoutInflater inflater;
    Context context;
    public static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);
    public Map<Integer, Book> bookDataList = new HashMap<Integer, Book>();

    private Set<Integer> processingBooks = new HashSet<Integer>();
    
    public ListViewAdapter(Context context, Handler handler) {
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.context = context;
        this.loadBookDialog = new LoadbookDialog(context);
        this.internalhandler = handler;
    }

    public int getCount() {
        return count;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }


    /**
     * @param book
     */
    private void readAction(final Book book) {
        Intent intent = new Intent();
        intent.setClass(context, ReadBookActivity.class);
        Bundle bundle = new Bundle();
        Book tmp = SingleDAO.getinstance().getBookshelf(book.getBookid());
        bundle.putSerializable("book", (Serializable) tmp);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = inflater.inflate(R.layout.book_item, null);

        TextView title = (TextView) convertView.findViewById(R.id.title);
        final Book book = bookDataList.get(position);

        if (book == null) {
            return convertView;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("《").append(book.getTitle()).append("》");
        title.setText(Html.fromHtml(sb.toString()));

        TextView intro = (TextView) convertView.findViewById(R.id.content);
        intro.setText(book.getServerLastChapter());
        ImageView download = (ImageView) convertView.findViewById(R.id.download_book);
        ImageView inter = (ImageView) convertView.findViewById(R.id.start_read);
        
        RelativeLayout main = (RelativeLayout) convertView.findViewById(R.id.main);
        
        if (SingleDAO.getinstance().isBookExist(book.getBookid())) {
            download.setVisibility(View.GONE);
            inter.setVisibility(View.VISIBLE);
            inter.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View paramView) {

                    readAction(book);

                }

            });
            
            main.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View paramView) {

                    readAction(book);

                }

            });

        } else {
            download.setVisibility(View.VISIBLE);
            inter.setVisibility(View.GONE);
            download.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    donwloadAction(book);
                    
                }

            });
            main.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View paramView) {

                    donwloadAction(book);

                }

            });
        }

        return convertView;
    }

    /**
     * @param book
     */
    private void donwloadAction(final Book book) {
        // 不要重复点击
        if (processingBooks.contains(book.getBookid())) {
            return;
        } 
        
        boolean netSataus = false;
        boolean isWifi = false;
        ConnectivityManager cwjManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        cwjManager.getActiveNetworkInfo();

        if (cwjManager.getActiveNetworkInfo() != null) {
            netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
            isWifi = (cwjManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI ? true : false);
        }
        
        if (!netSataus) {
            Toast.makeText(context, "请连接网络再试一下", Toast.LENGTH_SHORT).show();
        } else if (!isWifi) {
            final Dialog dialog = new AlertDialog.Builder(((Activity)context).getParent() == null ? context : ((Activity)context).getParent()).setTitle("温馨提示")
                    .setMessage("亲，你正在使用2/3G网络，加载速度会比较慢，建议在WIFI网络做此操作哦")
                    .setPositiveButton("继续，等不及了", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                            
                            handleDownload(book);
                        }
                    }).setNegativeButton("好的", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        }
                    }).create();

            dialog.show();
        } else {
            handleDownload(book);
        }
    }
    
    private void handleDownload(final Book book) {
        // 积分规则
        if (SingleDAO.getinstance().getBookshelfList().size() < EndUser.getInstance().getBookCount()) {
            // 书架不足
            threadPool.schedule(new Runnable() {

                @Override
                public void run() {

                    if (Utils.hasNetwork(context)) {
                        downloadFile(book.getDownloadPath(), book.getBookid() + ".zip", book);
                    } else {
                        internalhandler.post(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(context, "网络不给力", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }
            }, 0, TimeUnit.MILLISECONDS);
        } else if (EndUser.getInstance().getGold() + Constant.operation.get("bookshelf") >= 0) {
           
            final Dialog dialog = new AlertDialog.Builder(((Activity)context).getParent() == null ? context : ((Activity)context).getParent()).setTitle("书海小助手温馨提示")
                    .setMessage("需要增加书架容量咯（" + Constant.operation.get("bookshelf") + "积分/三本")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                            
                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    if (HttpUtils.goldOperation("bookshelf")) {
                                        EndUser.getInstance().updateGold(Constant.operation.get("bookshelf"));
                                        EndUser.getInstance().setBookCount(EndUser.getInstance().getBookCount() + 3);
                                        threadPool.schedule(new Runnable() {

                                            @Override
                                            public void run() {

                                                if (Utils.hasNetwork(context)) {
                                                    downloadFile(book.getDownloadPath(), book.getBookid() + ".zip", book);
                                                } else {
                                                    internalhandler.post(new Runnable() {

                                                        @Override
                                                        public void run() {
                                                            Toast.makeText(context, "网络不给力", Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                                }

                                            }
                                        }, 0, TimeUnit.MILLISECONDS);

                                    } else {
                                        internalhandler.post(new Runnable() {
                                            public void run() {
                                                Toast.makeText(context, "服务器异常", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                        Message msg = new Message();
                                        msg.what = 1;
                                        internalhandler.sendMessage(msg);
                                    }

                                }
                            }).start();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        }
                    }).create();

            dialog.show();
        } else if (EndUser.getInstance().getGold() + Constant.operation.get("bookshelf") < 0) {
            final Dialog dialog = new AlertDialog.Builder(((Activity)context).getParent() == null ? context : ((Activity)context).getParent()).setTitle("温馨提示")
                    .setMessage("尊敬的用户，书架不够用啦(" + Constant.operation.get("bookshelf") + "积分/扩三本)，您的积分不足")
                    .setPositiveButton("获取积分", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                            
                            AdWallManager.openAppOffers((Activity)context);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        }
                    }).create();

            dialog.show();

        }
    }
    
    private int downLoadFileSize;
    private int fileSize_b;
    private LoadbookDialog loadBookDialog;
    protected Handler internalhandler;

    public void downloadFile(String fileURL, String fileName, final Book book) {
        downLoadFileSize = 0;
        fileSize_b = 0;
        StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        double avail_sd_space = (double) stat_fs.getAvailableBlocks() * (double) stat_fs.getBlockSize();
        // double GB_Available = (avail_sd_space / 1073741824);
        double MB_Available = (avail_sd_space / 10485783);
        // System.out.println("Available MB : " + MB_Available);
        Log.d("MB", "" + MB_Available);
        
        processingBooks.add(book.getBookid());
        
        internalhandler.post(new Runnable() {

            @Override
            public void run() {

                loadBookDialog = new LoadbookDialog(((Activity) context).getParent() == null ? context : ((Activity) context).getParent());
                loadBookDialog.show();
                loadBookDialog.tips.setText("请求中...");

            }
        });
        
        try {
            File root = new File(Constant.DIR);
            if (root.exists() && root.isDirectory()) {

            } else {
                root.mkdir();
            }
            Log.d("CURRENT PATH", root.getPath());
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setConnectTimeout(10000);
            c.connect();
            int fileSize = c.getContentLength() / 1048576;
            Log.d("FILESIZE", "" + fileSize);
            if (MB_Available <= fileSize) {
                c.disconnect();
                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {

                        Toast.makeText(context, "空间不足", Toast.LENGTH_LONG).show();
                        loadBookDialog.dismiss();
                    }
                });
                return;
            }

            String zipFilename = root.getPath() + "/" + fileName;
            String unzipFilePath = root.getPath() + "/" + fileName.substring(0, fileName.length() - 4) + "/";
            FileOutputStream f = new FileOutputStream(new File(zipFilename));

            internalhandler.post(new Runnable() {

                @Override
                public void run() {

                    loadBookDialog.progress.setMax(fileSize_b);

                }
            });

            InputStream in = c.getInputStream();
            fileSize_b = c.getContentLength();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {

                if (loadBookDialog.cancel) {
                    // TODO
                }

                f.write(buffer, 0, len1);
                downLoadFileSize += len1;
                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {

                        loadBookDialog.progress.setProgress(downLoadFileSize);
                        float result = ((float) downLoadFileSize / fileSize_b) * 100;
                        loadBookDialog.tips.setText("小说加载中 - " + (int) result + "%");

                    }
                });
            }
            f.close();

            internalhandler.post(new Runnable() {

                @Override
                public void run() {

                    loadBookDialog.progress.setProgress(downLoadFileSize);
                    loadBookDialog.tips.setText("加载完成，处理中");
                }
            });
            UnZip.unzip(zipFilename, unzipFilePath);

            HttpUtils.addBookshelf(book.getBookid());
            SingleDAO.getinstance().insertBookshelf(book);

            internalhandler.post(new Runnable() {

                @Override
                public void run() {

                    loadBookDialog.tips.setText("处理完毕");

                    loadBookDialog.dismiss();

                    internalhandler.post(new Runnable() {

                        @Override
                        public void run() {

                            notifyDataSetChanged();
                        }
                    });
                    
                    Intent intent = new Intent();
                    intent.setClass(context, ReadBookActivity.class);
                    Bundle bundle = new Bundle();
                    Book tmp = SingleDAO.getinstance().getBookshelf(book.getBookid());
                    bundle.putSerializable("book", (Serializable) tmp);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            });
        } catch (Exception e) {

            Log.d("Downloader", e.getMessage());
            if (loadBookDialog.isShowing()) {
                loadBookDialog.dismiss();
            }
            MobclickAgent.onError(context);
        } finally {
            processingBooks.remove(book.getBookid());
        }
    }
}